<template>
  <common-edit-dialog
    :visible.sync="highSearchOpen"
    :button-loading="buttonLoading"
    @cancel="highSearchOpen = false"
    @submit="advanceFilterConfirm"
    :title="'高级筛选'"
  >
    <common-list-group>
      <div slot="group" class="custom-search-wrap">
        <div class="group-header-wrap">
          <div class="group-header-title">名称</div>
        </div>

        <common-tree
          ref="advancedTreeRef"
          isSlot
          :treeData="advancedTreeData"
          :treeProp="treeProp"
          search-placeholder="搜索"
        >
          <div
            slot-scope="{ scope }"
            class="tree-item-wrap"
            @click="advancedTreeClick(scope.data, scope.node)"
          >
            <common-carousel-text :content="scope.data.name" :font-size="14" />
            <el-popover
              popper-class="chart-type-list-popover"
              placement="right-start"
              width="150"
              trigger="hover"
            >
              <!--              <i slot="reference" class="iconfont icon-more"></i>-->
              <commonIcon
                iconName="icon-more"
                slot="reference"
                iconType="icon"
                :iconSize="16"
              ></commonIcon>
              <common-menu>
                <common-menu-item @click="treeDelete(scope.data)"
                  >删除</common-menu-item
                >
              </common-menu>
            </el-popover>
          </div>
        </common-tree>
      </div>
      <div class="right-content">
        <el-dropdown
          size="small"
          split-button
          type="primary"
          @command="toogleItem"
        >
          <span @click="toogleItem(AndORLabel === '或' ? 'OR' : 'AND')"
            >添加条件({{ AndORLabel }})</span
          >
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="AND">且条件</el-dropdown-item>
            <el-dropdown-item command="OR">或条件</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <div class="condition-generator">
          <QueryGenerator
            :relations="relations"
            ref="generator"
            :isLog="true"
          />
        </div>

        <div class="save-record">
          <el-checkbox v-model="addForm.checked" @change="changeSave"
            >保存查询条件</el-checkbox
          >
          <content-tip :tipType="'log_content_filter'"></content-tip>

          <div v-if="showRecordName" class="record-name">
            <span style="width: 52px">名称：</span>
            <el-input
              :maxlength="64"
              v-model="addForm.recordName"
              placeholder="请输入查询条件名称"
            ></el-input>
          </div>
        </div>
      </div>
    </common-list-group>
  </common-edit-dialog>
</template>

<script>
import {
  recordList,
  recordAdd,
  recordEdit,
  recordDelete,
} from "@/api/analysisCenter/log";
import QueryGenerator from "../QueryGenerator/index.vue";
import { deepClone } from "@/utils/index";
import { mapState } from "vuex";
import { generateSqlObj } from "@/utils/util";
import ContentTip from "../ContentTip/index.vue";
import commonIcon from "@/components/CommonIcon";
export default {
  name: "AdvancedFilter",
  components: { QueryGenerator, commonIcon, ContentTip },
  props: {},
  data() {
    return {
      highSearchOpen: false,
      advancedTreeData: [],
      addForm: {
        checked: false,
        recordName: "",
      },
      showRecordName: false,

      relations: ["OR", [{ fieldName: "", operator: "EQ", value: "" }]],

      oldRelations: [],
      currentId: "",
      treeProp: {
        children: "children",
        label: "name",
        disabled: false,
      },
      AndORLabel: "且",
      buttonLoading: false,
    };
  },
  computed: {
    ...mapState("log", ["typeMapList", "operatorList"]),
  },
  methods: {
    show() {
      this.highSearchOpen = true;
      this.setInitialRelations();
      this.AndORLabel = "且";
      this.advancedTreeData = [];
      this.currentId = "";
      this.addForm.recordName = "";
      this.addForm.checked = false;
      this.showRecordName = false;
      recordList().then((res) => {
        if (res && res.code === 200) {
          this.advancedTreeData = res.data;
        } else {
          this.advancedTreeData = [];
          this.handleListTips(res);
        }
      });
    },

    setInitialRelations() {
      this.relations = ["AND", [{ fieldName: "", operator: "EQ", value: "" }]];
      this.relations[1][0].fieldName = this.typeMapList[0].columnName;
      this.relations[1][0].operator =
        this.typeMapList[0].operatorList[0].paramValue;
    },

    //高级筛选  删除
    treeDelete(row) {
      this.$GlobalDeleteConfirm()
        .then(() => {
          recordDelete({ ids: row.id })
            .then((res) => {
              this.$GlobalSuccessMessage("删除成功");
              this.advancedTreeData = this.advancedTreeData.filter((item) => {
                return item.id !== row.id;
              });
              this.setInitialRelations();
              this.AndORLabel = "且";
              this.currentId = "";
              this.addForm.recordName = "";
              this.addForm.checked = false;
            })
            .finally(() => {});
        })
        .catch(() => {});
    },
    //高级筛选  保存记录勾选
    changeSave() {
      this.showRecordName = this.addForm.checked ? true : false;
    },

    //高级筛选  且或条件展示
    toogleItem(val) {
      this.AndORLabel = val === "AND" ? "且" : "或";

      this.oldRelations = deepClone(this.relations);
      this.$nextTick(() => {
        this.$refs.generator.createRelation(val, this.oldRelations);
      });
      console.log(this.relations);
    },

    //高级筛选 左边树
    advancedTreeClick(data, node) {
      this.currentId = data.id;
      let currentData = this.advancedTreeData.find((item) => {
        return item.id === data.id;
      });
      this.relations = JSON.parse(currentData.searchCond);
      if (this.currentId) {
        this.addForm.checked = true;
        this.addForm.recordName = currentData.name;
        this.showRecordName = true;
      }

      console.log(this.relations);
    },
    // 高级筛选确定
    advanceFilterConfirm() {
      let objCondition = generateSqlObj(this.relations);
      if (!objCondition) {
        this.$message.warning("请输入字段值");
        return;
      }

      if (this.addForm.checked && !this.addForm.recordName) {
        this.$message.warning("请输入名称");
        return;
      }

      if (this.addForm.checked) {
        if (this.currentId) {
          this.buttonLoading = true;
          recordEdit({
            id: this.currentId,
            name: this.addForm.recordName,
            searchCond: this.relations,
          })
            .then((res) => {
              if (res && res.code == 200) {
                this.$GlobalSuccessMessage("修改成功");
              } else {
                this.$GlobalErrorConfirm("修改失败", res.msg);
              }
            })
            .finally(() => {
              this.buttonLoading = false;
              this.currentId = "";
              this.addForm = { checked: false, recordName: "" };
            });
        } else {
          if (this.addForm.recordName && this.addForm.checked) {
            this.buttonLoading = true;
            recordAdd({
              name: this.addForm.recordName,
              searchCond: this.relations,
            })
              .then((res) => {
                if (res && res.code == 200) {
                  this.$GlobalSuccessMessage("新增成功");
                } else {
                  this.$GlobalErrorConfirm("新增失败", res.msg);
                }
              })
              .finally(() => {
                this.buttonLoading = false;
                this.currentId = "";
                this.addForm = { checked: false, recordName: "" };
              });
          }
        }
      }

      this.$emit("toSubmit", this.relations);
    },

    closeDialog() {
      this.highSearchOpen = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.condition-generator {
  margin: 10px 0;
}
.save-record {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: -10px;
  height: 40px;
  .record-name {
    margin-left: 20px;
    display: flex;
    width: 100%;
    align-items: center;
  }
  ::v-deep .el-checkbox__label {
    height: 20px;
    line-height: 20px;
  }
}
.custom-search-wrap {
  margin: -18px -10px 0 -15px;
  .group-header-wrap {
    height: 30px;
  }
  .tree-item-wrap {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    &:hover {
      .iconfont {
        opacity: 1;
      }
    }
    .iconfont {
      opacity: 0;
      transition: opacity 0.15s linear;
    }
  }
}
</style>
